package com.miniapp.entity;

import lombok.Data;

import java.io.Serializable;

/**
 * 统一API响应结果封装
 * @author author
 * @date 2025-09-01 10:24
 */
@Data
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    // 成功状态码
    public static final int SUCCESS_CODE = 200;
    // 错误状态码 - 系统异常
    public static final int ERROR_CODE_SYSTEM = 500;
    // 错误状态码 - 参数校验
    public static final int ERROR_CODE_PARAM_VALID = 400;
    // 错误状态码 - 数据库异常
    public static final int ERROR_CODE_DB = 501;
    // 错误状态码 - SQL注入
    public static final int ERROR_CODE_SQL_INJECTION = 403;

    private int code;
    private String msg;
    private T data;
    // 分页参数
    private long total;
    private long current;
    private long size;

    // 私有构造方法
    private R() {}

    /**
     * 成功返回（无数据）
     */
    public static <T> R<T> success() {
        R<T> result = new R<>();
        result.code = SUCCESS_CODE;
        result.msg = "操作成功";
        return result;
    }

    /**
     * 成功返回（带数据）
     */
    public static <T> R<T> success(T data) {
        R<T> result = new R<>();
        result.code = SUCCESS_CODE;
        result.msg = "操作成功";
        result.data = data;
        return result;
    }

    /**
     * 成功返回（带分页数据）
     */
    public static <T> R<T> success(T data, long total, long current, long size) {
        R<T> result = new R<>();
        result.code = SUCCESS_CODE;
        result.msg = "操作成功";
        result.data = data;
        result.total = total;
        result.current = current;
        result.size = size;
        return result;
    }

    /**
     * 错误返回
     */
    public static <T> R<T> error(int code, String msg) {
        R<T> result = new R<>();
        result.code = code;
        result.msg = msg;
        return result;
    }

    /**
     * 错误返回（默认系统错误码）
     */
    public static <T> R<T> error(String msg) {
        return error(ERROR_CODE_SYSTEM, msg);
    }
}
